<template>
  <div class="nav-space">
    <div class="tabs-wrap fixed">
      <slot></slot>
    </div>
    <div class="nav-space"></div>
    <div class="line fixed"
         :style="lineStyle"></div>
  </div>
  <router-view v-slot="{ Component }">
    <keep-alive>
      <transition name="fade"
                  mode="out-in">
        <component :is="Component" />
      </transition>
    </keep-alive>
  </router-view>
</template>

<script>
export const TABS_KEY = Symbol('ep')
import { useChildren } from '@vant/use'
import { reactive, toRefs, nextTick, onMounted } from 'vue'
import { onBeforeRouteUpdate, useRoute, useRouter } from 'vue-router'
export default {
  props: {
    lineColor: {
      type: String,
      required: false,
      default: '#4073f5'
    }
  },
  setup (props) {
    var {
      children,
      linkChildren
    } = useChildren(TABS_KEY)
    var state = reactive({
      inited: false,
      position: '',
      lineStyle: {},
      currentIndex: 0
    })
    const router = useRouter()
    const route = useRoute()
    const computeCurrentIndex = (fullpath) => {
      const computeIndex = children.findIndex(tab => {
        return tab.to === fullpath
      })
      computeIndex !== -1 && (state.currentIndex = computeIndex)
    }
    onBeforeRouteUpdate((to, from, next) => {
      computeCurrentIndex(to.fullPath)
      setLine()
      next()
    })
    const setLine = () => {
      const currentIndex = state.currentIndex
      nextTick(() => {
        var lineStyle = {
          width: 100 / children.length * .5 + '%',
          height: '3px',
          'border-radius': '2px',
          'background': props.lineColor,
          'transition-duration': '.3s',
          transform: "translateX(" + (children[currentIndex].$el.offsetLeft
            + children[currentIndex].$el.offsetWidth / 2) + "px) translateX(-50%)"
        };
        state.lineStyle = lineStyle;
      });
    }

    onMounted(() => {
      computeCurrentIndex(route.fullPath)
      setLine()
    })
    linkChildren({})
    return {
      ...toRefs(state)
    }
  }
}
</script>

<style scoped>
.tabs-wrap {
  display: flex;
  align-content: center;
  align-items: center;
  height: 44px;
  color: #333333;
  font-size: 13px;
  background: #fff;
  justify-content: space-around;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}
.fade-enter,
.fade-leave-to {
  opacity: 0;
}
</style>